package com.example.mybatisplusdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.mybatisplusdemo.mapper.UserMapper;
import com.example.mybatisplusdemo.model.domain.Recharge;
import com.example.mybatisplusdemo.mapper.RechargeMapper;
import com.example.mybatisplusdemo.service.IRechargeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 用户充值表 服务实现类
 * </p>
 *
 * @author lqj
 * @since 2025-07-01
 */
@Service
public class RechargeServiceImpl extends ServiceImpl<RechargeMapper, Recharge> implements IRechargeService {

    @Autowired
    private RechargeMapper rechargeMapper;

    @Autowired
    private UserMapper userMapper;

    public void saveRechargeRequest(Long userId, BigDecimal amount) {
        Recharge entity = new Recharge();  // 实体类，不是 Mapper
        entity.setUserId(userId);
        entity.setAmount(amount);
        entity.setStatus((byte) 0); // 待处理状态，建议定义常量
        entity.setCreateTime(LocalDateTime.now());
        rechargeMapper.insert(entity);
    }

    @Override
    public int clearProcessed() {
        // 删除 status 不等于 0 的记录（1: 同意，2: 拒绝）
        QueryWrapper<Recharge> wrapper = new QueryWrapper<>();
        wrapper.ne("status", 0);  // 只删处理过的
        return baseMapper.delete(wrapper);
    }


    @Override
    public List<Recharge> getAllPendingOrHandled() {
        return rechargeMapper.selectAllPendingOrHandled();
    }

    // RechargeServiceImpl.java
    @Transactional
    public boolean approve(Long requestId, boolean approved) {
        // 1. 先查询必要数据（无需锁）
        Recharge request = getById(requestId);
        if (request == null || request.getStatus() != 0) {
            return false;
        }

        // 2. 原子更新状态
        byte targetStatus = approved ? (byte) 1: (byte) 2;
        int updated = rechargeMapper.updateStatusIfPending(
                requestId,
                targetStatus
        );

        if (updated == 0) return false;

        // 3. 审批通过才增加余额
        if (approved) {
            // 使用查询时获取的金额和用户ID
            userMapper.increaseBalance(request.getUserId(), request.getAmount());
        }
        return true;
    }


}
